﻿using System;
using TaiwuModdingLib.Core.Plugin;
using UnityEngine;
using HarmonyLib;
using System.Reflection;

namespace CricketCheat
{
    [PluginConfig("CricketCheat", "com.ryanli.plugins.CricketCheat", "1")]
    public class Main : TaiwuRemakeHarmonyPlugin
    {
        //斗蛐蛐必胜
        public static bool NeverLose;

        //显示蛐蛐
        public static bool ShowCricket;

        //抓捕概率
        public static bool SingLevel;

        public override void Dispose()
        {
            base.Dispose();
            unsetShowCricket();
        }

        public override void Initialize()
        {
            this.HarmonyInstance.PatchAll(typeof(InitCatchPlace_Path));
            this.HarmonyInstance.PatchAll(typeof(CheckWinBeforeFight_Path));
        }

        public override void OnModSettingUpdate()
        {
            base.OnModSettingUpdate();
            ModManager.GetSetting(base.ModIdStr, "NeverLose", ref Main.NeverLose);
            bool showCricket = Main.ShowCricket;
            ModManager.GetSetting(base.ModIdStr, "ShowCricket", val: ref showCricket);
            if (Main.ShowCricket && !showCricket)
            {
                unsetShowCricket();
            }
            Main.ShowCricket = showCricket;
            ModManager.GetSetting(base.ModIdStr, "SingLevel", ref Main.SingLevel);
            if (Main.SingLevel)
            {
                this.HarmonyInstance.PatchAll(typeof(OnClickCatchPlace));
            } else
            {
                UI_CatchCricket ui = UIElement.CatchCricket.UiBaseAs<UI_CatchCricket>();
                if (ui != null)
                {
                    this.HarmonyInstance.Unpatch(ui.GetType().GetMethod("OnClickCatchPlace"), HarmonyPatchType.All);
                }
            }
        }

        public void unsetShowCricket()
        {
            UI_CatchCricket ui = UIElement.CatchCricket.UiBaseAs<UI_CatchCricket>();
            if (ui != null)
            {
                Traverse uiTrv = Traverse.Create(ui);
                RectTransform root = uiTrv.Field("_catchPlaceRoot").GetValue<RectTransform>();
                for (int i = 0; i < 21; i++)
                {
                    var parent = root.GetChild(i).transform;
                    var cricketTrans = parent.Find("cricketView");
                    if (cricketTrans == null)
                    {
                        GameObject.Destroy(cricketTrans.gameObject);
                    }
                    var textTrans = parent.Find("cricketName");
                    if (textTrans != null)
                    {
                        GameObject.Destroy(textTrans.gameObject);
                    }
                    parent.Find("PlaceImg").gameObject.SetActive(true);
                }
            }
        }
    }
}
